<?php

namespace app\api\controller\user;

use app\api\controller\Controllers;
use app\api\service\OAuth2 as OAuth2Service;
use app\api\service\Token;
use app\api\service\UserNumber;
use app\api\service\UserInfo as UserInfoService;
use think\Request;

class OAuth2 extends Controllers
{
    /**
     * 登录凭证
     *
     * @return \think\Response
     */
    public function logonCredentials( OAuth2Service $oAuth2 )
    {
        $get = $this->request->only(['code', 'state'], 'get');
        $this->validate($get, 'app\api\validate\OAuth2.oAuth2');
        $state = data_get($get, 'state');
        $userCredentials = $oAuth2->handler( data_get($get, 'code'), $state );
        $unionid = data_get($userCredentials, 'unionid');
        //注册或绑定
        $binding = (new UserNumber())->unionidBinding($unionid, data_get($userCredentials,'openid'), $state);
        if ( $binding['code'] === 200 ) {
            unset($binding['data']['password']);
            unset($binding['data']['create_at']);
            unset($binding['data']['update_at']);
            $fieldConfig = config('field.user_number');
            return success([
                'token' => Token::get($binding['data']),
                'language' => $fieldConfig['language'],
                'language_type' => $binding['data']['language']??0
            ]);
        }
        return failed($binding['message']);
    }

    /**
     * 添加用户信息
     *
     * @return \think\Response
     */
    public function addInfo(Request $request)
    {
        $post = $this->request->only(['nickname','head_url','gender','country','province','city','lat','lon'], 'post');
        $this->validate($post, 'app\api\validate\UserInfo');
        $uid = $request->userInfo['id'];
        $saveUserInfo = (new UserInfoService())->saveUserInfo($post, $uid);
        if ( $saveUserInfo ) {
            return success();
        }
        return failed('用户信息插入失败');
    }

}
